<?php
require_once('TVB/PWORKS/mvc/IFilter.iface.php');
require_once('TVB/PWORKS/mvc/IAction.iface.php');
require_once('TVB/PWORKS/message/Message.class.php');

class LogFilter implements IFilter {
	private $_fail;
	private $_succ;
	public function before(IAction &$action) {

		return null;
	}

	public function after(IAction &$action) {

		$this->_fail = $action->getErrors();
		$this->_succ = $action->getInfos();

		try{
			$log = new audit_log();
			//add failed log
			if (!empty($this->_fail))
			{
				foreach ($this->_fail as $key=>$fail_log)
				{
					if (strstr($key, ":"))
					{
						$key_arr = explode(":",$key);
					}
					else
					{
						break;
					}

					$log->item_type_id = item_type::getItemIDByName($key_arr[0]);
					$log->item_id = isset($key_arr[2]) ? $key_arr[2] : 0;
					$log->modified_at = date("Y-m-d H:i:s");
					$log->modified_by = CommonUtils::get_user();
					$log->status = ($key_arr[1] == AC::LOG_OP_DELETE) ? AC::STATUS_DELETED : AC::STATUS_NEW;
					$log->remarks= isset($fail_log[0]) ? (is_array($fail_log[0]->content) ? json_encode($fail_log[0]->content) : $fail_log[0]->content) : "";
					$log->action = isset($key_arr[1]) ? $key_arr[1] : 0;
					$log->data = is_array($fail_log[0]->details) ? json_encode($fail_log[0]->details) : $fail_log[0]->details;
					if ($log->item_id) Model::$dbo['w']->save($log);
				}
			}

			//add success log
			if (!empty($this->_succ))
			{
				foreach ($this->_succ as $key=>$succ_log)
				{
					$key_arr = explode(":",$key);
					$log->item_type_id = item_type::getItemIDByName($key_arr[0]);
					$log->item_id = $key_arr[2];
					$log->modified_at = date("Y-m-d H:i:s");
					$log->modified_by = CommonUtils::get_user();
					$log->status = ($key_arr[1] == AC::LOG_OP_DELETE) ? AC::STATUS_DELETED : AC::STATUS_NEW;
					$log->remarks= $succ_log[0]->content;
					$log->action = $key_arr[1];
					$log->data = $succ_log[0]->details;
					Model::$dbo['w']->save($log);
				}
			}
		}
		catch(Exception $e)
		{
			return null;
		}
		return null;
	}
}
?>
